<?php

namespace app\admin\model;

use app\common\controller\Send;
use think\Db;

class OauthOrder extends \app\common\model\OauthOrder
{
    use Send;

    /**
     * 列表
     * @param $where
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($where)
    {
        $sql = static::field('id, order_sn, type, oauth_id, oauth_nickname, lang_id, money, integral, customer_id, 
        coupon_id, coupon_name, coupon, pay_money, pay_type, share_uid, share_nickname, share_commission, create_time, update_time');

        if ($where) {
            $sql->where($where);
        }
        //订单倒序
        $sql->order('id desc');
        // 总金额（临时的where条件 刚入职 不乱清理数据 ）
        $money = $sql->where('pay_money','<',10000)->sum('pay_money');
        // 总佣金
        $commission = $sql->sum('share_commission');

        $data = $sql->paginate(null, false, ['query' => request()->param()]);

        foreach($data as $k=>$v){
            $data[$k]['oauth_nickname'] = $v['oauth_nickname']?$v['oauth_nickname']:self::selectOauthNickName($v['oauth_id']);
        } 
        $langIds = [];
        $orderIds = [];
        $customerIds = [];
        foreach ($data->items() as $key => $value) {
            $langIds[$value['lang_id']] = $value['lang_id'];
            $orderIds[$value['id']] = $value['id'];
            $customerIds[$value['customer_id']] = $value['customer_id'];
        }

        // 语种
        $lang = [];
        if ($langIds) {
            $lang = Lang::getColumn($langIds);
        }

        // 获取班级类型
        $class = [];
        if ($orderIds) {
            $class = OauthOrderClass::getColumnByOrder($orderIds);
        }

        $customer = [];
        if ($customerIds) {
            $customer = CustomerService::getColumn($customerIds);
        }

        $model = $data->each(function ($item, $key) use ($class, $lang, $customer) {
            $item = self::dealData($item, $class, $lang, $customer);
            return $item;
        });

        // 获取总记录数
        $count = $model->total();

        return [
            'model' => $model,
            'count' => $count,
            'money' => $money,
            'commission' => $commission
        ];
    }

    /**
     * 订单详情
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($id)
    {
        $model = static::field('id, order_sn, type, oauth_id, oauth_nickname, lang_id, money, integral, customer_id, 
        coupon_id, coupon_name, coupon, pay_money, pay_type, share_uid, share_nickname, share_commission, remark, create_time, update_time')
            ->where(['id' => $id])
            ->find();
        if ($model) {
            $model = $model->toArray();
            // 语种名称
            $lang = Lang::getColumn([$model['lang_id']]);
            // 购买班级
            $class = OauthOrderClass::getColumnByOrder([$model['id']]);
            // 客服
            $customer = CustomerService::getColumn($model['customer_id']);
            // 处理数据
            $model = self::dealData($model, $class, $lang, $customer);
        }
        return $model;
    }

    public static function dealData($item, $class, $lang, $customer)
    {
        $item['pay_type'] = self::attributes('pay_type', $item['pay_type']);
        $item['type'] = self::attributes('type', $item['type']);
        $item['lang_id'] = isset($lang[$item['lang_id']]) ? $lang[$item['lang_id']] : '未知';
        $item['customer_id'] = isset($customer[$item['customer_id']]) ? $customer[$item['customer_id']] : '暂无';
        $item['class_1'] = isset($class[$item['id']][1]) ? $class[$item['id']][1] : '否';
        $item['class_2'] = isset($class[$item['id']][2]) ? $class[$item['id']][2] : '否';
        $item['class_3'] = isset($class[$item['id']][3]) ? $class[$item['id']][3] : '否';
        $item['create_time'] = get_datetime($item['create_time']);
        $item['update_time'] = get_datetime($item['update_time']);
        $item['share_uid'] = $item['share_uid'] ? : '无';
        $item['share_nickname'] = $item['share_nickname'] ? : '无';
        $item['share_commission'] = $item['share_commission'] > 0 ?  $item['share_commission'] : '无';
        $item['coupon_name'] = $item['coupon_name'] ? : '暂无';
        $item['coupon'] = $item['coupon'] > 0 ?  $item['coupon'] : '暂无';
        $item['integral'] = $item['integral'] > 0 ?  $item['integral'] : '暂无';
        return $item;
    }

    /**
     * 添加订单
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function saveOne($data)
    {
        // 通过语种id 和 班级类型 查找班级id
        $classIdsArr = LangClass::getClassByType($data['lang_id'], $data['type']);
        $classIds = implode(',', array_keys($classIdsArr));
        if (empty($classIds)) {
            return self::sendResult(603, [], '班级不存在');
        }

        // 通过用户id查找用户openid
        $oauth = Oauth::getOne($data['oauth_id']);
        if (empty($oauth)) {
            return self::sendResult(603, [], '用户不存在');
        }

        $openid = $oauth['openid'];
        $outTradeNo = OauthOrder::getOrderSn();
        $totalFee = $data['pay_money'];
        // 附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用String(128)，怕字段不够装，只能简写了
        $attach = json_encode([
            'cs' => $classIds, // 班级ids
            'rm' => $data['integral'], // 积分抵扣金额
            'cn' => $data['coupon_id'], // 优惠券id
            'key' => '', // 用户的分享key
            'kf' => $data['customer_id'], // 客服id
            't' => self::TYPE_ADMIN, // 类型，后台添加
            'pt' => $data['pay_type'] // 支付方式
        ]);

        // 支付回调处理
        $payResult = OauthOrder::orderPaid($openid, $outTradeNo, $totalFee, $attach, $data['remark'], $msg,$oauth);
        if ($payResult === false) {
            return self::sendResult(603, [], $msg);
        }
        return self::sendResult(self::$okCode);
    }

    /**
     * 添加备注
     * @param $data
     */
    public static function remark($data)
    {
        $model = static::get($data['id']);
        if ($model) {
            $model->remark = isset($data['remark']) ? $data['remark'] : '';
            $model->update_time = time();
            $model->save();
        }
    }

    /**
     * 获取订单信息
     * @param $oauthId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function buyInfo($oauthId)
    {
        // 获取用户信息
        $oauth = Oauth::getOne($oauthId);
        if (empty($oauth)) {
            return [
                'oauth' => [
                    'id' => 0,
                    'nickname' => '',
                    'phone' => '',
                    'integral' => 0
                ],
                'customers' => [],
                'reduceMoney' => 0,
                'coupon' => []
            ];
        }

        // 客服列表
        $customers = CustomerService::getColumn();

        // 积分可抵扣的金额
        $reduceMoney = 0;
        if ($oauth['integral'] > 0) {
            $reduceMoney = Config::getReduceMoney($oauth['integral']);
        }

        // 优惠券
        $coupon = Coupon::getListAll($oauthId);
        return [
            'oauth' => $oauth,
            'customers' => $customers,
            'reduceMoney' => $reduceMoney,
            'coupon' => $coupon
        ];
    }
    
    /**
     * 删除订单
     * @param $id
     */
    public static function deleteOne($id)
    {
        $model = static::get($id);
        if ($model) {
            $model->delete();
            OauthOrderClass::deleteOne($id);
        }
    }
    
    
    
    public static function selectOauthNickName($oauth_id){
        $where['id'] = $oauth_id;
        $ret = DB::table('oauth')->field('phone,is_bind_device,device_info')->where($where)->find();
        if($ret['phone']){
            return $ret['phone'];
        }else{
            return $ret['device_info'];
        }
    }
}